package cn.jinjimi.app.custom.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.czt.mp3recorder.MP3Recorder;
import com.facebook.common.executors.CallerThreadExecutor;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.BaseDataSubscriber;
import com.facebook.datasource.DataSource;
import com.facebook.datasource.DataSubscriber;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.image.CloseableBitmap;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import cn.jinjimi.base.Task.TaskExecutor;
import cn.jinjimi.base.preference.PreferenceManager;
import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.ImageUtils;
import cn.jinjimi.base.util.LogUtil;
import cn.jinjimi.base.util.SharePlatForm;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.base.util.ViewUtils;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.framework.helper.annotation.EventTraceParam;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.ShareProxy;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.bean.EventDataField;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.bean.QuesCode;
import cn.jinjimi.app.controller.CustomerController;
import cn.jinjimi.app.controller.event.CardDetailEvent;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.MakeCardExitEvent;
import cn.jinjimi.app.controller.event.MakeCardShareBtnEvent;
import cn.jinjimi.app.controller.event.SendCardSucc;
import cn.jinjimi.app.controller.event.UploadRecordCardEvent;
import cn.jinjimi.app.custom.entity.Custom;
import cn.jinjimi.app.custom.ui.activity.SelectCustomActivity;
import cn.jinjimi.app.entity.CardListBean;
import cn.jinjimi.app.entity.RecordCardBean;
import cn.jinjimi.app.main.dialog.CommAlertDialog;
import cn.jinjimi.app.main.dialog.ShareDialog;
import cn.jinjimi.app.main.extend.BaseActivity;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;
import cn.jinjimi.app.main.fragment.CardSendSuccFragment;
import cn.jinjimi.app.bean.SharePrefKeys;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 贺卡的制作
 * 祝福语的编辑
 * 贺卡的生成
 * 分享贺卡
 * Created by Jinsen on 2015/6/3.
 */
public class MakeCardFragment extends BaseFragment implements View.OnClickListener, AudioManager.OnAudioFocusChangeListener {

    private final String TAG = this.getClass().getSimpleName();

    int mType = 0;
    String mTitle = null;
    String mId = null;
    String mCardId = null;
    String mBirthDay = null;
    String mIconUrl = null;
    Rect mBlessRect = null;

    CardListBean.CardBean cardBean = null;

    EditText mReceiverEt = null;
    ImageView mCardImgIv = null;
    EditText mBlessingsEt = null;
    ImageView mClientSelectBtn = null;

    View mRecoredView = null;
    ImageView mRecordStartIv = null;
    ImageView mRecordStateIv = null;
    TextView mRecordLenTv = null;
    TextView mRecordResetTv = null;

    View mAlertView = null;
    ImageView mAlertBgIv = null;
    ImageView mAlertStateIv = null;
    TextView mAlertMsgTv = null;
    TextView mAlertCountDownTv = null;
    ImageView mAlertLoadIv = null;

    ImageView mCardPreviewIv = null;
    View mCardEditView = null;

    private RelativeLayout rlInfo;

    private View mLoadCardView = null;
    private TextView mLoadMsgView = null;
    private ImageView mLoadStateIv = null;
    private ProgressBar mLoadingPb = null;

    Bitmap mCardBgBitmap = null;
    private Bitmap mShareBitmap;

    //贺卡制作状态
    boolean mIsMakeCarding = false;

    private MP3Recorder mRecorder;
    private boolean isRecording = false;
    private String recordName;
    private MediaPlayer mediaPlayer;
    private boolean isPlaying;

    private int btnType = 1;//1，录音 2，正在录音 3，播放录音

    private static final int STATUS_READY_TO_RECORD = 1; // 准备录音
    private static final int STATUS_RECORDING = 2; // 正在录音
    private static final int STATUS_READY_TO_PLAY = 3; // 准备播放
    private static final int STATUS_PLAYING = 4; // 正在播放

    CommAlertDialog mResultAlertDialog = null;
    TextView mResultAlertMsg = null;
    TextView mResultOkBtn = null;
    RelativeLayout mLayout_record;

    //转动动画
    RotateAnimation mRefreshAnim = null;

    //是否可以触摸
    boolean mClickEnable = true;

    private int mRecordMaxLen = 30000;//30s
    private int mReadVoiceSizeSpace = 200;//0.2s;
    private int mRecordCountDown = mRecordMaxLen / mReadVoiceSizeSpace;

    boolean mHasStart = false;

    boolean mHasChangeName = false;

    String mEnter = null;

    private AudioManager mAudioManager;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_make_card_layout;
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    protected void initView() {
        mType = getArguments().getInt("type", Constants.REMIND_TYPE_BIRTHDAY);
        mTitle = getArguments().getString("title");
        mId = getArguments().getString("id");
        mCardId = getArguments().getString("cardId");
        mEnter = getArguments().getString("enter");

        cardBean = (CardListBean.CardBean) getArguments().getSerializable("cardBean");
        if (StringUtils.isEmpty(mCardId) && cardBean != null) {
            mCardId = String.valueOf(cardBean.getId());
        }

        mReceiverEt = (EditText) findView().findViewById(R.id.ed_name);
        mCardImgIv = (ImageView) findView().findViewById(R.id.make_card_edit_pic);
        mBlessingsEt = (EditText) findView().findViewById(R.id.make_card_edit_blessings_editText);

        mClientSelectBtn = (ImageView) findView().findViewById(R.id.img_select);
        mClientSelectBtn.setVisibility(View.GONE);

        rlInfo = (RelativeLayout) findView().findViewById(R.id.rl_info);

        mLoadCardView = findView().findViewById(R.id.activity_list_load_layout);
        mLoadMsgView = (TextView) findView().findViewById(R.id.load_state_msg_textView);
        mLoadStateIv = (ImageView) findView().findViewById(R.id.load_state_fail_tryagain_imageView);
        mLoadingPb = (ProgressBar) findView().findViewById(R.id.load_state_ing_progressBar);

        if (mType != Constants.REMIND_TYPE_BIRTHDAY) {
            mReceiverEt.setVisibility(View.GONE);
            mClientSelectBtn.setVisibility(View.GONE);
//        } else if (StringUtils.isEmpty(mId)) {
//            mClientSelectBtn.setVisibility(View.VISIBLE);
//            mNotGetCustom = true;
//        }
        } else {
            mClientSelectBtn.setVisibility(View.VISIBLE);
        }

        mCardPreviewIv = (ImageView) findView().findViewById(R.id.make_card_preview_img);
        mCardEditView = findView().findViewById(R.id.make_card_edit_layout);

        mRecoredView = findView().findViewById(R.id.make_card_record_state_bg);
        mRecordStartIv = (ImageView) findView().findViewById(R.id.make_card_record_start);
        mRecordResetTv = (TextView) findView().findViewById(R.id.make_card_record_to_reset);
        mRecordLenTv = (TextView) findView().findViewById(R.id.make_card_record_len);
        mRecordStateIv = (ImageView) findView().findViewById(R.id.make_card_record_state_imageView);

        mAlertView = findView().findViewById(R.id.make_card_alert_layout);
        mAlertView.setVisibility(View.GONE);
        mAlertBgIv = (ImageView) findView().findViewById(R.id.make_card_alert_bg_imageView);
        mAlertStateIv = (ImageView) findView().findViewById(R.id.make_card_alert_state_imageView);
        mAlertMsgTv = (TextView) findView().findViewById(R.id.make_card_alert_msg_textView);
        mAlertLoadIv = (ImageView) findView().findViewById(R.id.make_card_alert_load);
        mAlertCountDownTv = (TextView) findView().findViewById(R.id.make_card_alert_countdown_textview);
        mLayout_record = (RelativeLayout) findView().findViewById(R.id.layout_record);

    }

    private void getAudioFocus() {
        if (mAudioManager != null) {
            mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        }
    }

    protected void initListener() {
        mClientSelectBtn.setOnClickListener(this);

        findView().findViewById(R.id.load_state_fail_tryagain_imageView).setOnClickListener(this);

        mRecordStartIv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mIsMakeCarding || !mClickEnable)
                    return true;

                getAudioFocus();

                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN://开始录音
                        startRecord();
                        return true;
                    case MotionEvent.ACTION_CANCEL://停止录音
                    case MotionEvent.ACTION_UP:
                        stopRecord();
                        return true;
                }
                return false;
            }
        });

        mRecoredView.setOnClickListener(this);
        mRecordResetTv.setOnClickListener(this);
    }

    private void handleCardBean(CardListBean.CardBean cardBean) {
        if (null != cardBean) {
            String mStyle = cardBean.getStyle();
            LogUtil.d(TAG, "style :: " + mStyle);
            if (StringUtils.isNotEmpty(mStyle)) {
                String style[] = mStyle.split(";");

                int length = style.length;
                try {
                    if (length > 0)
                        cardBean.setContentColor(style[0].split(":")[1]);
                    if (length > 1)
                        cardBean.setSenderColor(style[1].split(":")[1]);
                    if (length > 2)
                        cardBean.setReceiverColor(style[2].split(":")[1]);

                    if (length > 3) {
                        Pattern pattern = Pattern.compile("content_rect:\\(([\\d]+),([\\d]+),([\\d]+),([\\d]+)\\)");
                        Matcher matcher = pattern.matcher(style[3]);
                        if (matcher.find()) {

                            int x1 = Integer.parseInt(matcher.group(1));
                            int y1 = Integer.parseInt(matcher.group(2));
                            int x2 = Integer.parseInt(matcher.group(3));
                            int y2 = Integer.parseInt(matcher.group(4));

                            mBlessRect = new Rect(x1, y1, x2, y2);
                        }
                    }
                } catch (Exception e) {
                    cardBean.setContentColor(null);
                    cardBean.setSenderColor(null);
                    cardBean.setReceiverColor(null);
                    LogUtil.d(TAG, "解析样式错误");
                }

                LogUtil.d(TAG, "style.mBlessRect " + mBlessRect);
            }
        }
    }

    protected void initData() {
        if (cardBean == null || cardBean.getImageUrl() == null) {
            loadCardDetail();
            return;
        }
        handleCardBean(cardBean);
        mReceiverEt.setText(mTitle);
        mReceiverEt.setSelection(mReceiverEt.getText().toString().trim().length());

        ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(Uri.parse(cardBean.getImageUrl())).build();
        DataSource<CloseableReference<CloseableImage>> dataSource = Fresco.getImagePipeline().fetchDecodedImage(imageRequest, getActivity());

        DataSubscriber dataSubscriber = new BaseDataSubscriber<CloseableReference<CloseableImage>>() {
            @Override
            protected void onNewResultImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
                if (!dataSource.isFinished()) {
                    LogUtil.d("Not yet finished - this is just another progressive scan.");
                }

                CloseableReference<CloseableImage> imageReference = dataSource.getResult();
                if (imageReference != null) {
                    try {
                        CloseableBitmap image = (CloseableBitmap) imageReference.get();
                        Bitmap loadedImage = image.getUnderlyingBitmap();
                        if (getActivity() == null || getActivity().isFinishing())
                            return;

                        mCardBgBitmap = loadedImage;

                        TaskExecutor.runTaskOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                setStyle();

                                mCardImgIv.setImageBitmap(mCardBgBitmap);
                                mLoadCardView.setVisibility(View.GONE);
                            }
                        });

                    } finally {
                        dataSource.close();
                        CloseableReference.closeSafely(imageReference);
                    }
                }
            }

            @Override
            protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
                TaskExecutor.runTaskOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.toastMessage(getActivity(), "下载贺卡图片失败，请重试。");
                        getActivity().finish();
                    }
                });
            }
        };

        dataSource.subscribe(dataSubscriber, CallerThreadExecutor.getInstance());

        mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);

        mediaPlayer = new MediaPlayer();
        readyRecord();
        changView(btnType);

        ImageView imgAvatar = (ImageView) findView().findViewById(R.id.img_avatar);
        TextView tvName = (TextView) findView().findViewById(R.id.tv_name);
        imgAvatar.setImageURI(Uri.parse(AccountManager.getInstance().getAccount().avatar));
        tvName.setText(AccountManager.getInstance().getAccount().realName);
    }

    //设置不同贺卡的样式
    private void setStyle() {
        if (StringUtils.isNotEmpty(cardBean.getReceiverColor())) {
            int color = Color.parseColor(cardBean.getReceiverColor());
            mReceiverEt.setTextColor(color);
        }
        if (StringUtils.isNotEmpty(cardBean.getContentColor())) {
            int color = Color.parseColor(cardBean.getContentColor());
            mBlessingsEt.setTextColor(color);
        }
        mBlessingsEt.setText(cardBean.getDefaultBlessing());

        if (!checkActivityExit()) {
            int dp10 = getActivity().getResources().getDimensionPixelSize(R.dimen.dp_10);
            int bgW = AndroidUtils.getWindowWidth(getActivity()) - 2 * dp10;
            int bgH = bgW;

            if (mCardBgBitmap != null) {
                int cardH = mCardBgBitmap.getHeight();
                int cardW = mCardBgBitmap.getWidth();

                bgH = (int) (bgW / ((float) cardW / cardH));
                ViewUtils.setHeight(mCardImgIv, bgH);
            }

            if (mBlessRect != null) {
                int dp5 = getResources().getDimensionPixelSize(R.dimen.dp_5);
                int ml = bgW * mBlessRect.left / 100 + dp5;
                int mt = bgH * mBlessRect.top / 100 + dp5;
                int mr = bgW * mBlessRect.right / 100 + dp5;
                int mb = bgH * mBlessRect.bottom / 100 + dp5;
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mBlessingsEt.getLayoutParams();
                lp.setMargins(ml, mt, mr, mb);
                lp.width = RelativeLayout.LayoutParams.WRAP_CONTENT;
                lp.height = bgH - mt - mb;
            }
        }
    }

    //开始录音
    private void startRecord() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            btnType = STATUS_RECORDING;

            changView(btnType);

            showAlertState(1);

            mRecordCountDown = mRecordMaxLen / mReadVoiceSizeSpace;

            record();
        } else {
            ToastUtils.toastMessage(getActivity(), "请插入您的SD卡！");
        }
    }

    int mReadyTime = 0;

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (mHandler == null) return;
            int recordSize = mRecorder.getVolume();
            LogUtil.d(TAG, "record voice size : " + recordSize + mRecorder.isRecording());
            mHandler.sendEmptyMessageDelayed(0, mReadVoiceSizeSpace);
            if (recordSize == 0 && !mHasStart) {
                mAlertStateIv.setImageBitmap(null);
                mAlertMsgTv.setText("准备中...");

                if (mReadyTime > 5) {
                    mReadyTime = 0;
                    recordFail();
                    return;
                }
                mReadyTime++;
            } else {
                if (!mHasStart) {
                    mAlertMsgTv.setText("正在录音...");
                    mHasStart = true;
                    mAlertCountDownTv.setText(null);
                    mReadyTime = 0;
                }

                if (mRecordCountDown > 25) {
                    int voiceSize = recordSize / 100;
                    if (voiceSize < 5) {
                        mAlertStateIv.setImageResource(R.drawable.icon_record_enlarge1);
                    } else if (voiceSize < 10) {
                        mAlertStateIv.setImageResource(R.drawable.icon_record_enlarge2);
                    } else {
                        mAlertStateIv.setImageResource(R.drawable.icon_record_enlarge3);
                    }
                } else {
                    mAlertStateIv.setImageBitmap(null);
                    mAlertCountDownTv.setText(String.valueOf(1 + (mRecordCountDown - 1) * 200 / 1000));
                    mAlertMsgTv.setText("录音倒计时");
                }
                if (mRecordCountDown < 2) {
                    mHandler.removeMessages(0);
                    stopRecord();
                    return;
                }
                mRecordCountDown--;
            }

        }
    };

    //停止录音
    private void stopRecord() {
        mHasStart = false;
        if (!isRecording) return;
        isRecording = !isRecording;
        mHandler.removeMessages(0);
        mRecorder.stop();
        File recordFile = new File(getRecordFilePath(recordName));
        if (!recordFile.exists()) {

            mAlertLoadIv.clearAnimation();
            mAlertView.setVisibility(View.GONE);
            resultAlertDialog(1);

            mVoiceLen = 0;
            btnType = STATUS_READY_TO_RECORD;

        } else {
            try {
                mediaPlayer.setDataSource(getRecordFilePath(recordName));
                mediaPlayer.prepare();
                mVoiceLen = mediaPlayer.getDuration();
                mediaPlayer.reset();
            } catch (Exception e) {
                if (recordFile.length() > 1024)
                    mVoiceLen = -1;
            }

            LogUtil.e(TAG, "record file size = " + recordFile.length());
            if ((mVoiceLen > -1 && mVoiceLen < 2000)) {//录音时长太短或太长
                showAlertState(2);
                mVoiceLen = 0;
                btnType = STATUS_READY_TO_RECORD;
            } else {
                showAlertState(5);
                btnType = STATUS_READY_TO_PLAY;
            }
        }

        changView(btnType);

    }

    //录音失败
    private void recordFail() {
        mHasStart = false;
        isRecording = false;
        mHandler.removeMessages(0);
        mRecorder.stop();

        mAlertLoadIv.clearAnimation();
        mAlertView.setVisibility(View.GONE);
        resultAlertDialog(5);

        mVoiceLen = 0;
        btnType = STATUS_READY_TO_RECORD;

        changView(btnType);
    }

    /**
     * 结果状态提示
     *
     * @param state
     */
    private void resultAlertDialog(int state) {
        if (mResultAlertDialog == null) {
            mResultAlertDialog = ((BaseActivity) getActivity()).getAlertDialog().setTitle("确定要重新录制吗？");

            mResultAlertMsg = mResultAlertDialog.getTitle();
            mResultOkBtn = mResultAlertDialog.getRightBtn();
        }

        switch (state) {
            case 1://录音失败提示
                mResultOkBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mResultAlertDialog.dismissDialog();
                    }
                });
                mResultAlertMsg.setText("录音失败，请稍后再试");
                mResultAlertDialog.showDialog(CommAlertDialog.Style.ONE_BUTTON);
                break;

            case 2://重新录制
                mResultOkBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        reRecord();
                        mResultAlertDialog.dismissDialog();
                    }
                });
                mResultAlertMsg.setText("确定要重新录制吗？");
                mResultAlertDialog.showDialog(CommAlertDialog.Style.TWO_BUTTON);
                break;

            case 3://制作贺卡失败
                mIsMakeCarding = false;
                mResultOkBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mResultAlertDialog.dismissDialog();
                    }
                });
                mResultAlertMsg.setText("生成贺卡失败，\n请再次点击\"分享\"");
                mResultAlertDialog.showDialog(CommAlertDialog.Style.ONE_BUTTON);
                break;
            case 4://是否放弃编辑
                mResultOkBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mResultAlertDialog.dismissDialog();
                        getActivity().finish();
                    }
                });
                mResultAlertMsg.setText("是否放弃编辑贺卡");
                mResultAlertDialog.showDialog(CommAlertDialog.Style.TWO_BUTTON);
                break;
            case 5://请开启权限
                mResultOkBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mResultAlertDialog.dismissDialog();
                    }
                });
                mResultAlertMsg.setText("请先开启你手机的录音功能，\n以正常使用此功能。");
                mResultAlertDialog.showDialog(CommAlertDialog.Style.ONE_BUTTON);
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mRecorder == null)
            return;
        mRecorder.stop();
        new File(getRecordFilePath(recordName)).delete();

        mediaPlayer.release();
        mediaPlayer = null;

        mAudioManager.abandonAudioFocus(this);
    }

    @Override
    public void onClick(View v) {
        if (mIsMakeCarding || mAlertView.getVisibility() == View.VISIBLE)
            return;
        switch (v.getId()) {
            case R.id.make_card_record_state_bg:
                switch (btnType) {
                    case STATUS_READY_TO_PLAY://播放录音
                        btnType = STATUS_PLAYING;
                        tryPlay();
                        break;
                    case STATUS_PLAYING: // 正在播放
                        btnType = STATUS_READY_TO_PLAY;
                        stopPlay();
                        break;
                }
                changView(btnType);
                break;

            case R.id.make_card_record_to_reset:// 重录
                resultAlertDialog(2);
                break;

            case R.id.img_select:
                SelectCustomActivity.launch(getActivity(), QuesCode.QuestSelectClientCode);
                break;
            case R.id.load_state_fail_tryagain_imageView:
                loadCardDetail();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case QuesCode.QuestSelectBlessingsCode:
                    String mBlessingsStr = data.getStringExtra("content");
                    if (StringUtils.isNotEmpty(mBlessingsStr))
                        mBlessingsEt.setText(mBlessingsStr);
                    break;
                case QuesCode.QuestSelectClientCode:
                    if (data == null)
                        return;
                    Custom custom = (Custom) data.getSerializableExtra(BundleKey.PARAM_CUSTOM);
                    if (custom != null) {
                        mHasChangeName = true;
                        mTitle = custom.name;
                        mId = String.valueOf(custom.customerId);
                        mBirthDay = custom.birthday;
                        mIconUrl = custom.avatar;
                        mReceiverEt.setText(mTitle);
                        mReceiverEt.setSelection(mReceiverEt.getText().toString().trim().length());
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @EventTrace(EventID.APP_SHARE_CLICK)
    private void share(@EventTraceParam(value = EventDataField.ParamFrom, selector = {EventID.FROM_CUSTOM_TIPS_BIRTH, EventID.FROM_CUSTOM_TIPS_FESTIVAL}) boolean isBirthday) {
        String title = AccountManager.getInstance().getAccount().realName + "给你发贺卡";

        ShareDialog.Builder builder = new ShareDialog.Builder();
        builder.SharePlatForm(SharePlatForm.getShareMultiPlatforms());
        if (StringUtils.isNotEmpty(mRecordCardBean.getGreeting_record().getVoice_duration()) &&
                !mRecordCardBean.getGreeting_record().getVoice_duration().equals("0")) {
            builder.ImageUrl(cardBean.getCoverUrl())
                    .ShareUrl(mRecordCardBean.getShare_url())
                    .Content(cardBean.getDefaultBlessing())
                    .ShareType(ShareProxy.ShareType.COMMON)
                    .Title(title);
        } else {
            builder.Bitmap(mShareBitmap).ShareType(ShareProxy.ShareType.IMAGE);
        }
        builder.FromUrl(isBirthday ? EventID.FROM_CUSTOM_TIPS_BIRTH : EventID.FROM_CUSTOM_TIPS_FESTIVAL);

        ShareDialog mShareDialog = builder.build(getActivity());

        mShareDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                mCardPreviewIv.clearAnimation();
                mCardPreviewIv.setVisibility(View.GONE);
                mIsMakeCarding = false;
            }
        });
        mShareDialog.setOnSharedListener(new ShareDialog.SharedListener() {

            @Override
            public void onSuccess() {
                sendSucc();
            }

            @Override
            public void onCancel() {
            }

            @Override
            public void onFail() {
            }

            @Override
            public void onStart() {
                analyseStart(PreferenceManager.getStringData(SharePrefKeys.PREF_SHARE_ID), String.valueOf(mRecordCardBean.getGreeting_record().getRecord_id()), cardBean.getHolidayId() == 0);
            }

            @EventTrace(EventID.APP_SHARE_TYPE_ID)
            private void analyseStart(@EventTraceParam(EventDataField.ParamPostion) String position,
                                      @EventTraceParam(EventDataField.ParamId) String id,
                                      boolean holidayType) {
            }
        });
        mShareDialog.show();
    }

    private void sendSucc() {
        //节日贺卡
        if (mType != Constants.REMIND_TYPE_BIRTHDAY) {
            CustomerController.uploadSendCardRecord(cardBean.getDefaultBlessing(), mId, mCardId);
            EventBus.getDefault().post(new SendCardSucc());
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
        } else {//生日贺卡

            if (StringUtils.isEmpty(mId)) {
                mTitle = mReceiverEt.getText().toString().trim();
                getActivity().setTitle("发送成功");
                FragmentManager fm = getActivity().getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                CardSendSuccFragment mcf = new CardSendSuccFragment();
                Bundle data = new Bundle();
                data.putString("name", mTitle);
                data.putString("id", mId);
                data.putString("cardId", mCardId);
                data.putString("iconUrl", mIconUrl);
                data.putString("blessings", cardBean.getDefaultBlessing());
                mcf.setArguments(data);
                ft.add(R.id.content_fragment, mcf, "SENDSUCC_ADD");
                ft.commitAllowingStateLoss();
                ft.remove(this);
                ((ToolBarCommonActivity) getActivity()).setRightBtnVisibility(false);
            } else {
                CustomerController.uploadSendCardRecord(cardBean.getDefaultBlessing(), mId, mCardId);
                EventBus.getDefault().post(new SendCardSucc());
                getActivity().setResult(Activity.RESULT_OK);
                getActivity().finish();
            }
        }
    }

    //准备录音
    private void readyRecord() {
        mVoiceLen = 0;
        recordName = System.currentTimeMillis() + "";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(getRecordFolderName());
            if (!file.exists())
                file.mkdirs();
            mRecorder = new MP3Recorder(new File(getRecordFilePath(recordName)));
        } else {
            ToastUtils.toastMessage(getActivity(), "请插入您的SD卡！");
        }

    }

    //重新录制
    private void reRecord() {
        stopPlay();
        mVoiceLen = 0;
        btnType = STATUS_READY_TO_RECORD;
        changView(btnType);
    }

    /* 试听 */
    private void tryPlay() {
        if (isPlaying) {
            stopPlay();
        }
        try {
            mediaPlayer.setDataSource(getRecordFilePath(recordName));
            mediaPlayer.prepare();
            mediaPlayer.start();
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    stopPlay();
                    btnType = STATUS_READY_TO_RECORD;
                    mVoiceLen = 0;
                    new File(getRecordFilePath(recordName)).delete();
                    changView(btnType);
                    return false;
                }
            });

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    btnType = STATUS_READY_TO_PLAY;
                    stopPlay();
                    changView(btnType);
                }
            });
            isPlaying = true;
        } catch (IllegalStateException | IllegalArgumentException | SecurityException | IOException e) {
            e.printStackTrace();
            LogUtil.e(TAG, e.getMessage());
            stopPlay();
            btnType = STATUS_READY_TO_RECORD;
            changView(btnType);
        }
    }

    /* 停止播放 */
    private void stopPlay() {
        mediaPlayer.reset();
        isPlaying = false;
    }

    /* 录音 */
    private void record() {
        if (!isRecording) {
            isRecording = !isRecording;
            try {
                mRecorder.start();
            } catch (Exception e) {
                e.printStackTrace();
                isRecording = !isRecording;
            }
        } else {
            mRecorder.stop();
        }
    }

    private void changView(int type) {
        switch (type) {
            case STATUS_READY_TO_RECORD:
                mRecordStartIv.setVisibility(View.VISIBLE);
                mRecordStateIv.setVisibility(View.GONE);
                mRecordLenTv.setVisibility(View.GONE);
                mRecordResetTv.setVisibility(View.GONE);
                mRecordStartIv.setImageResource(R.drawable.icon_recorder);
                break;

            case STATUS_RECORDING:
                mRecordStartIv.setVisibility(View.VISIBLE);
                mRecordStateIv.setVisibility(View.GONE);
                mRecordLenTv.setVisibility(View.GONE);
                mRecordResetTv.setVisibility(View.GONE);
                mRecordStartIv.setImageResource(R.drawable.icon_recorder_blue);
                break;

            case STATUS_READY_TO_PLAY:
                int len = mVoiceLen % 1000 == 0 ? mVoiceLen / 1000 : mVoiceLen / 1000 + 1;
                mRecordStartIv.setVisibility(View.GONE);
                mRecordStateIv.setVisibility(View.VISIBLE);
                mRecordLenTv.setVisibility(View.VISIBLE);
                mRecordLenTv.setText(len + "''");
                mRecordResetTv.setVisibility(View.VISIBLE);
                mRecordStateIv.setImageResource(R.drawable.icon_record_to_play_white);
                break;

            case STATUS_PLAYING:
                mRecordStartIv.setVisibility(View.GONE);
                mRecordStateIv.setVisibility(View.VISIBLE);
                mRecordLenTv.setVisibility(View.VISIBLE);
                mRecordResetTv.setVisibility(View.VISIBLE);
                mRecordStateIv.setImageResource(R.drawable.icon_record_pause);
                break;
        }
    }

    //上传贺卡信息
    private void uploadRecordCardInfo() {
        AndroidUtils.hideSoftKeyBoard(getActivity().getWindow());

        if (mType == Constants.REMIND_TYPE_BIRTHDAY && mReceiverEt.isShown() && mReceiverEt.length() == 0) {
            ToastUtils.toastMessage(getActivity(), "还没输入客户的名字呢！");
            return;
        }

        cardBean.setDefaultBlessing(mBlessingsEt.getText().toString().trim());
        if (StringUtils.isEmpty(cardBean.getDefaultBlessing())) {
            ToastUtils.toastMessage(getActivity(), "在发送贺卡时，请附上祝福语吧！");
            return;
        }

        if (cardBean.getDefaultBlessing().length() < 4 || cardBean.getDefaultBlessing().length() > 84) {
            ToastUtils.toastMessage(getActivity(), "听说祝福语的长度在4到84个字更配哦！");
            return;
        }

        String receiverName = mReceiverEt.getText().toString().trim();

        if (mRecordCardBean != null) {
            RecordCardBean.GreetRecord record = mRecordCardBean.getGreeting_record();
            if (record.getBlessing().equals(cardBean.getDefaultBlessing())
                    && record.getCustomer_name().equals(receiverName)
                    && (mId == null || (mId != null && mId.equals(String.valueOf(record.getCustomer_id()))))
                    && ((StringUtils.isEmpty(record.getVoice_duration()) && mVoiceLen < 1)//有录音或者没有录音
                    || String.valueOf(mVoiceLen).equals(record.getVoice_duration()))) {
                share(mType == Constants.REMIND_TYPE_BIRTHDAY);
                return;
            }
        }

        mIsMakeCarding = true;
        showAlertState(0);

        CustomerController.uploadRecordCardInfo(cardBean.getDefaultBlessing(), mId, receiverName, cardBean.getId(), mType, mVoiceLen);

    }

    //合成后的卡片保存路径
    String mCardPath = null;

    private void buldBitmap() {
        rlInfo.setVisibility(View.VISIBLE);
        if (mType == Constants.REMIND_TYPE_BIRTHDAY && mReceiverEt.isShown()) {
            mBlessingsEt.setText("To " + mReceiverEt.getText().toString() + "：" + mBlessingsEt.getText().toString());
        }
        mBlessingsEt.setEnabled(false);
        mIsMakeCarding = true;

        final ScaleAnimation mTakeShotAnim = new ScaleAnimation(1.1f, 0.8f, 1.1f, 0.8f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        mTakeShotAnim.setDuration(500);
        mTakeShotAnim.setFillAfter(true);
        mTakeShotAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                rlInfo.setVisibility(View.GONE);
                mBlessingsEt.setEnabled(true);
                if (mType == Constants.REMIND_TYPE_BIRTHDAY && mReceiverEt.isShown()) {
                    mBlessingsEt.setText(mBlessingsEt.getText().toString().substring(mBlessingsEt.getText().toString().indexOf("：") + 1));
                }
                showAlertState(4);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

        TaskExecutor.scheduleTaskOnUiThread(100, new Runnable() {
            @Override
            public void run() {
                mShareBitmap = takeShotPic();
                mCardPreviewIv.setImageBitmap(mShareBitmap);
                mCardPreviewIv.setVisibility(View.VISIBLE);
                mCardPreviewIv.startAnimation(mTakeShotAnim);
            }
        });
    }

    //截屏
    private Bitmap takeShotPic() {
        mCardEditView.setDrawingCacheEnabled(true);
        mCardEditView.buildDrawingCache();
        Bitmap bitmap = mCardEditView.getDrawingCache();
        int width = mCardEditView.getWidth();
        int height = mCardEditView.getHeight();
        // 根据坐标点和需要的宽和高创建bitmap
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bitmap = ImageUtils.getBitmap(bos.toByteArray(), width, height);
        mCardEditView.setDrawingCacheEnabled(false);
        return bitmap;
    }

    /**
     * 状态提示框
     *
     * @param state 0 制作贺卡
     *              1 录音中
     *              2 录音太短
     *              3 录音时间太长 超过30秒
     *              4 贺卡制作完成
     *              5 录音完成
     */
    private void showAlertState(int state) {
        switch (state) {
            case 0://制作贺卡
                mAlertCountDownTv.setVisibility(View.GONE);
                mAlertView.setVisibility(View.VISIBLE);
                mAlertStateIv.setVisibility(View.INVISIBLE);
                if (mRefreshAnim == null) {
                    mRefreshAnim = new RotateAnimation(0.0f, 360.0f,
                            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                            0.5f);
                    mRefreshAnim.setDuration(1000);
                    mRefreshAnim.setRepeatCount(-1);
                }
                mAlertLoadIv.clearAnimation();
                mAlertLoadIv.startAnimation(mRefreshAnim);
                mAlertLoadIv.setVisibility(View.VISIBLE);
                mAlertMsgTv.setText("贺卡制作中");
                break;
            case 1://录音中
                mAlertCountDownTv.setVisibility(View.VISIBLE);
                mAlertView.setVisibility(View.VISIBLE);
                mAlertStateIv.setVisibility(View.VISIBLE);
                mAlertStateIv.setBackgroundColor(Color.TRANSPARENT);
                if (mRefreshAnim == null) {
                    mRefreshAnim = new RotateAnimation(0.0f, 360.0f,
                            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                            0.5f);
                    mRefreshAnim.setDuration(1000);
                    mRefreshAnim.setRepeatCount(-1);
                }
                mAlertStateIv.setImageBitmap(null);
                mAlertLoadIv.clearAnimation();
                mAlertLoadIv.startAnimation(mRefreshAnim);
                mAlertLoadIv.setVisibility(View.VISIBLE);
                mAlertMsgTv.setText("准备中...");
                mHandler.sendEmptyMessageDelayed(0, mReadVoiceSizeSpace);
                break;
            case 2://录音太短
                mAlertCountDownTv.setVisibility(View.GONE);
                mAlertStateIv.setImageBitmap(null);
                mAlertStateIv.setBackgroundResource(R.drawable.icon_record_warning);
                mAlertLoadIv.setVisibility(View.GONE);
                mAlertMsgTv.setText("录音时间太短了");
                mClickEnable = false;

                TaskExecutor.scheduleTaskOnUiThread(1000, new Runnable() {
                    @Override
                    public void run() {
                        mClickEnable = true;
                        if (!isRecording) mAlertView.setVisibility(View.GONE);
                    }
                });

                break;
            case 3://录音太长，超过30秒
                mAlertCountDownTv.setVisibility(View.GONE);
                mAlertStateIv.setImageBitmap(null);
                mAlertStateIv.setBackgroundResource(R.drawable.icon_record_warning);
                mAlertLoadIv.setVisibility(View.GONE);
                mAlertMsgTv.setText("录音请控制在30秒以内");
                mClickEnable = false;
                TaskExecutor.scheduleTaskOnUiThread(1500, new Runnable() {
                    @Override
                    public void run() {
                        mClickEnable = true;
                        if (!isRecording) mAlertView.setVisibility(View.GONE);
                    }
                });
                break;

            case 4://贺卡制作完成
                mAlertCountDownTv.setVisibility(View.GONE);
                mAlertStateIv.setBackgroundResource(R.drawable.icon_complete_white);
                mAlertLoadIv.setVisibility(View.GONE);
                mAlertMsgTv.setText("贺卡制作完成");
                mAlertStateIv.setImageBitmap(null);
                mAlertLoadIv.setVisibility(View.GONE);
                mClickEnable = false;
                TaskExecutor.scheduleTaskOnUiThread(1000, new Runnable() {
                    @Override
                    public void run() {
                        mClickEnable = true;
                        if (!isRecording) mAlertView.setVisibility(View.GONE);
                        share(mType == Constants.REMIND_TYPE_BIRTHDAY);
                    }
                });
                break;
            case 5://录音完成
                mAlertCountDownTv.setVisibility(View.GONE);
                mAlertStateIv.setBackgroundResource(R.drawable.icon_complete_white);
                mAlertLoadIv.setVisibility(View.GONE);
                mAlertMsgTv.setText("录音完成");
                mAlertStateIv.setImageBitmap(null);
                mAlertLoadIv.setVisibility(View.GONE);
                mClickEnable = false;
                TaskExecutor.scheduleTaskOnUiThread(1000, new Runnable() {
                    @Override
                    public void run() {
                        mClickEnable = true;
                        if (!isRecording) mAlertView.setVisibility(View.GONE);
                    }
                });
                break;
        }
    }

    /**
     * 上传
     *
     * @param filePath 录音文件路径
     */
    private void upLoadVoice(int recordId, final String filePath) {

    }

    private boolean hasEditForCard() {
        if (mVoiceLen > 0)//有录音
            return true;

        if (mRecordCardBean != null)//有生成过贺卡
            return true;

        if (mHasChangeName)//重选选择客户
            return true;

        String inputRec = mReceiverEt.getText().toString().trim();
        if (StringUtils.isEmpty(mTitle) && StringUtils.isNotEmpty(inputRec)
                || StringUtils.isNotEmpty(mTitle) && !inputRec.equals(mTitle))
            return true;

        return cardBean != null && !mBlessingsEt.getText().toString().equals(cardBean.getDefaultBlessing());

    }

    private void loadCardDetail() {
        mLoadingPb.setVisibility(View.VISIBLE);
        mLoadStateIv.setVisibility(View.GONE);
        mLoadMsgView.setText("正在加载贺卡...");
        CustomerController.getCardById(mCardId);
    }

    /**
     * 分享按钮被点击
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMakeCardShareBtnEvent(MakeCardShareBtnEvent event) {
        if (mIsMakeCarding || mAlertView.getVisibility() == View.VISIBLE)
            return;

        if (mCardBgBitmap == null) {
            ToastUtils.toastMessage(getActivity(), "正在下载贺卡图片，请稍候...");
            return;
        }
        uploadRecordCardInfo();
    }

    /**
     * 按返回键返回
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMakeCardExitEvent(MakeCardExitEvent event) {
        if (hasEditForCard())
            resultAlertDialog(4);
        else
            getActivity().finish();
    }

    /**
     * 分享贺卡信息返回
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUploadRecordCardEvent(UploadRecordCardEvent event) {
        switch (event.state) {
            case DataEvent.SUCC:
                mRecordCardBean = event.data;
                if (mRecordCardBean != null && mRecordCardBean.getGreeting_record() != null) {

                    if (StringUtils.isNotEmpty(mRecordCardBean.getGreeting_record().getVoice_duration())
                            && !mRecordCardBean.getGreeting_record().getVoice_duration().equals("0")) {// 有录音的贺卡
                        String filePath = getRecordFilePath(recordName);
                        //上传声音
//                        CommonController.uploadFile()
                        upLoadVoice(mRecordCardBean.getGreeting_record().getRecord_id(), filePath);
                    } else {
                        buldBitmap();
                    }
                }
                break;
            case DataEvent.FAIL:
                mAlertLoadIv.clearAnimation();
                mAlertView.setVisibility(View.GONE);
                resultAlertDialog(3);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCardDetailEvent(CardDetailEvent event) {
        switch (event.state) {
            case DataEvent.SUCC:
                cardBean = event.data.getGreetingCard();
                mLayout_record.setVisibility(View.VISIBLE);
                initData();
                break;
            case DataEvent.FAIL:
                mLayout_record.setVisibility(View.GONE);
                mLoadingPb.setVisibility(View.GONE);
                mLoadStateIv.setVisibility(View.VISIBLE);
                mLoadMsgView.setText(R.string.loading_fail_for_click);
                break;
        }
    }

    private String getRecordFilePath(String name) {
        String path = Environment.getExternalStorageDirectory().getPath()
                + "/jinjimi/record/%s.mp3";

        return String.format(path, name);
    }

    private String getRecordFolderName() {
        return Environment.getExternalStorageDirectory().getPath()
                + "/jinjimi/record";
    }

    RecordCardBean mRecordCardBean = null;
    int mVoiceLen = 0;

    @Override
    public void onAudioFocusChange(int focusChange) {
    }

    //进入贺卡分享的入口
    public enum ENTER {
        HOLIDAY("holiday"),
        REMIND("remind"),
        INFO("info"),
        TOPRIGHT("topright");

        String enter;

        ENTER(String enter) {
            this.enter = enter;
        }

        public void setEnter(String enter) {
            this.enter = enter;
        }

        public String getEnter() {
            return enter;
        }
    }
}
